import React from "react";
import {Button, Col, Divider, Form, Input, message, Modal, Radio, Row, Spin, Table, Tag} from "antd";
import moment from "moment";
import {
    addDictItem,
    deleteDictItem,
    getDictItemList,
    updateDictItem
} from "../api/sysDict";

const {TextArea} = Input;

const FormItem = Form.Item;

const SysDictItemForm = Form.create()(props => {

    const {form, visible, handleAdd, handleModalVisible, detail} = props;

    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            handleAdd(fieldsValue);
            form.resetFields();
        });
    };

    const formItemLayout = {
        labelCol: {
            sm: {span: 6},
        },
        wrapperCol: {
            sm: {span: 18},
        },
    };

    return (
        <Modal
            width={600}
            title="字典值详情"
            maskClosable={false}
            visible={visible}
            okText={"保存"}
            onOk={okHandle}
            cancelText={"关闭"}
            onCancel={() => handleModalVisible(false)}
        >
            <Form className={"form_item_4 form_row_small_margin"}>
                <FormItem {...formItemLayout}
                          label="显示名称">
                    {form.getFieldDecorator('label', {
                        initialValue: detail.label,
                        rules: [{required: true, message: '不可为空'}],
                    })(
                        <Input className={"ant-col-12"}/>
                    )}
                </FormItem>
                <FormItem {...formItemLayout}
                          label="数据Key">
                    {form.getFieldDecorator('value', {
                        initialValue: detail.label,
                        rules: [{required: true, message: '不可为空'}],
                    })(
                        <Input className={"ant-col-12"}/>
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="备注">
                    {form.getFieldDecorator('remark', {
                        initialValue: detail.remark,
                        rules: [{required: true, message: '不可为空'}],
                    })(
                        <TextArea className={"ant-col-12"} rows={4}/>
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="状态">
                    {form.getFieldDecorator('status', {
                        initialValue: detail.status,
                        rules: [{required: true, message: '请选择状态'}],
                    })(
                        <Radio.Group className={"ant-col-12"}>
                            <Radio value="disable">禁用</Radio>
                            <Radio value="enable">启用</Radio>
                        </Radio.Group>
                    )}
                </FormItem>
            </Form>
        </Modal>
    )

});


class SysDictItem extends React.Component {

    state = {
        visible: false,
        loading: false,
        list: [],
        info: {},
        formValues: {},
        dictId: '',
        dictName: '',
    }


    columns = [{
        title: '显示名称',
        dataIndex: 'label',
        key: 'label',
    }, {
        title: '数据Key',
        dataIndex: 'value',
        key: 'value',
    }, {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark'

    }, {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        render: text => <Tag
            color={text === 'enable' ? 'blue' : 'red'}>{text ? text === 'enable' ? '启用' : '禁用' : ''}</Tag>

    }, {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,

    }, {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
            <span>
                    <a onClick={() => this.showDictInfo(record)}>修改</a>
                    <Divider type="vertical"/>
                    <a onClick={() => this.showConfirm(record.id)}>删除</a>
                </span>
        ),
    }];

    componentDidMount() {
        const {
            match: {
                params: {dictId, dictName},
            },
        } = this.props;

        document.title = '字典值管理';
        this.state.dictId = dictId;
        this.state.dictName = dictName;
        this.loadPageDictList(1);
    }

    loadPageDictList = page => {
        let ret = getDictItemList(page, 20, {...this.state.formValues, dictId: this.state.dictId});
        ret.then((res) => {
            this.setState({...this.state, list: res.data.data});
        })
    }

    showDictInfo = info => {
        this.setState({...this.state, info: info, visible: true})
    }

    handleModalVisible = flag => {
        this.setState({...this.state, info: {}, visible: flag})
    }

    showConfirm = id => {
        let that = this;
        Modal.confirm({
            title: '是否确认删除？',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteDictItem(that.state.dictId, id).then(res => {
                    if (res.data.code === 10000) {
                        message.success('删除成功');
                        this.loadPageDictList(1);
                    } else {
                        message.error(res.data.msg);
                    }
                })
            },
        });
    };

    saveDictInfo = formData => {
        let {id} = this.state.info;

        formData.dictId = this.state.dictId;

        let ret;
        if (id) {
            formData.id = id;
            ret = updateDictItem(formData);
        } else {
            ret = addDictItem(formData);
        }

        ret.then((res) => {
            message.success('保存成功！');
            this.handleModalVisible(false);
            this.loadPageDictList(1)
        });
    }

    handleSearch = e => {
        e.preventDefault();
        const {form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            this.state.formValues = fieldsValue;
            this.loadPageDictList(1);
        });
    };

    handleFormReset = () => {
        const {form} = this.props;
        form.resetFields();
        this.state.formValues = {};
        this.loadPageDictList(1);
    };

    renderSimpleForm = () => {
        const {
            form: {getFieldDecorator},
        } = this.props;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="显示名称">
                            {getFieldDecorator('label')(<Input placeholder="请输入"/>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span>
                          <Button type="primary" htmlType="submit">
                            查询
                          </Button>
                          <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                            重置
                          </Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }


    render() {

        let {list, dictName} = this.state;


        return (
            <div style={{margin: '40px', fontSize: '25px', fontWeight: 500}}>
                <div style={{marginBottom: '30px', display: 'flex', alignItems: 'center'}}>
                    <span>字典值管理</span>
                    <Tag color="blue" style={{marginLeft: '8px'}}>{dictName}</Tag>

                </div>
                <div style={{marginBottom: '40px'}}>{this.renderSimpleForm()}</div>

                <Button style={{marginBottom: '20px'}} type="primary" icon="plus" onClick={() => {
                    this.showDictInfo({});
                }}> 添加字典值 </Button>

                <Spin spinning={this.state.loading} delay={500}>

                    <Table columns={this.columns} rowKey={record => record.id} dataSource={list.rows}/>

                </Spin>

                <SysDictItemForm visible={this.state.visible} detail={this.state.info} handleAdd={this.saveDictInfo}
                                 handleModalVisible={this.handleModalVisible}/>
            </div>
        )
    }

}

// 表单控制
const _SysDict = Form.create()(SysDictItem);

export default _SysDict;
